package com.jiangxiaofei.citycloud.activity.user;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.EmptyUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.constants.PhoneId;
import com.jiangxiaofei.citycloud.mvp.MainConstant;
import com.jiangxiaofei.citycloud.mvp.MainPersenter;
import com.jiangxiaofei.citycloud.param.PhoneCodeParam;
import com.jiangxiaofei.citycloud.param.UserRegistParam;
import com.jiangxiaofei.citycloud.util.MD5Util;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author JiangXFei
 * @title 用户注册页面
 */

public class RegistActivity extends BaseActivity
        implements MainConstant.UserRegistView, MainConstant.PhoneIsRepeatView,
        MainConstant.GetPhoneCodeView {
    @InjectView(R.id.regist_et_phone)
    EditText registEtPhone;
    @InjectView(R.id.regist_et_pwd_one)
    EditText registEtPwdOne;
    @InjectView(R.id.regist_et_pwd_two)
    EditText registEtPwdTwo;
    @InjectView(R.id.regist_btn)
    Button registBtn;
    @InjectView(R.id.regist_tv_get_phone_code)
    TextView registTvGetPhoneCode;
    boolean isChecked = false;
    @InjectView(R.id.regist_et_phone_code)
    EditText registEtPhoneCode;
    private int time;
    private Timer timer;
    private UserRegistParam param;
    private MainConstant.PhoneIsRepeatPersenter mPhoneIsRepeatPersenter;
    private MainConstant.UserRegistPersenter mUserRegistPersenter;
    private MainConstant.GetPhoneCodePersenter getPhoneCodePersenter;
    private PhoneCodeParam phoneParam = new PhoneCodeParam();

    @Override
    protected void initView(Bundle savedInstanceState) {
        mActivity = this;
        mContext = this;
        setContentView(R.layout.activity_regist_layout);
        ButterKnife.inject(this);
        initTitle();
        phoneParam.setState(PhoneId.Regist);
        mPhoneIsRepeatPersenter = new MainPersenter(mContext, (MainConstant.PhoneIsRepeatView) mActivity);
        mUserRegistPersenter = new MainPersenter(mContext, (MainConstant.UserRegistView) mActivity);
        getPhoneCodePersenter = new MainPersenter(mContext, (MainConstant.GetPhoneCodeView) mActivity);
    }

    @Override
    protected void setListener() {

    }

    @OnClick({R.id.regist_btn, R.id.regist_tv_get_phone_code,})
    public void Onclick(View v) {
        switch (v.getId()) {
            case R.id.regist_btn:
                //注册
                if (isFormSuccesss()) {
                    mUserRegistPersenter.onRegistUser();
                }
                break;
            case R.id.regist_tv_get_phone_code:
                //获取验证码
                if (EmptyUtils.isEmpty(registEtPhone.getText().toString())) {
                    toast("请输入您的手机号码");
                    return;
                }
                phoneParam.setPhoneNum(registEtPhone.getText().toString());
                mPhoneIsRepeatPersenter.repeatIsPhone();
                break;
        }
    }

    public void setPhoneCode(final TextView textView) {
        Observable<Integer> observable = Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(final Subscriber<? super Integer> subscriber) {
                time = 60;
                timer = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        subscriber.onNext(time);
                        if (time == 0) {
                            subscriber.onCompleted();
                        }
                        time = time - 1;
                    }
                };
                timer.schedule(task, 1000, 1000);
            }
        });
        Observer<Integer> observer = new Observer<Integer>() {
            @Override
            public void onCompleted() {
                isChecked = false;
                textView.setText("发送验证码");
                timer.cancel();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer integer) {
                textView.setText("等待时间(" + integer + ")");
            }
        };
        observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        setCTitle("用户注册");
        setLeftOneBg(R.drawable.ic_back);
    }

    /**
     * 表单验证
     */
    private boolean isFormSuccesss() {
        //手机号码验证
        if (EmptyUtils.isEmpty(registEtPhone.getText().toString())) {
            toast("请输入您的手机号码");
            return false;
        } else {
            if (!RegexUtils.isMobileExact(registEtPhone.getText().toString())) {
                toast("请输入正确的手机号");
                return false;
            }
        }
        //密码验证
        if (EmptyUtils.isEmpty(registEtPwdOne.getText().toString())) {
            toast("请输入密码");
            return false;
        } else if (registEtPwdOne.getText().toString().length() >= 24 || registEtPwdOne.getText().toString().length() < 6) {
            toast("密码长度不小于6位，不大于24位。");
            return false;
        }
        //密码重复验证
        if (!registEtPwdTwo.getText().toString().equals(registEtPwdOne.getText().toString())) {
            toast("两次密码不一致");
            return false;
        }

        //验证码验证

        if (EmptyUtils.isEmpty(registEtPhoneCode.getText().toString()) || registEtPhoneCode.getText().toString().length() == 0) {
            toast("请输入验证码");
            return false;
        }
        String pwd = registEtPwdOne.getText().toString();
        String userPwd = MD5Util.MD5Salt2(pwd);
        param = new UserRegistParam(registEtPhone.getText().toString(), userPwd);
        param.setState(PhoneId.Regist);
        param.setCode(Integer.valueOf(registEtPhoneCode.getText().toString()));
        return true;
    }

    private void toast(String str) {
        Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public void onRegistSuccess(Object o) {
        Toast.makeText(mContext, "注册成功！", Toast.LENGTH_SHORT).show();
        mActivity.finish();
    }

    /**
     * 提交表单注册
     *
     * @return
     */
    @Override
    public UserRegistParam getRegistParam() {
        return param;
    }


    @Override
    public void repeatPhone(Object o) {
        if (!isChecked) {
            isChecked = true;
            setPhoneCode(registTvGetPhoneCode);
            getPhoneCodePersenter.getPhoneCode();
        }
    }

    /**
     * 获取手机号码
     *
     * @return 手机号
     */

    @Override
    public String getPhoneNum() {
        return registEtPhone.getText().toString();
    }

    @Override
    public PhoneCodeParam getCodePhoneNum() {
        return phoneParam;
    }

    @Override
    public void getPhoneCodeMsg(String msg) {
        toast(msg);
    }


}
